<script setup>
import { ref, nextTick } from "vue";
import { ElButton, ElInput, ElInputNumber, ElAvatar, ElMessage } from "element-plus";
import { Delete, Promotion, Location, Star, User } from "@element-plus/icons-vue";
import api from "@/util/request.js";

// ✅ 引入 markdown-it
import MarkdownIt from "markdown-it";
const md = new MarkdownIt({
  breaks: true,  // 自动把 \n 转成 <br>
  html: false,   // 不允许直接输出 HTML（避免安全风险）
});

// 请求头
const headers = { Authorization: localStorage.getItem('token') };

// 聊天状态
const message = ref("");
const chatRecords = ref([]);
const chatContent = ref(null);
const isLoading = ref(false);

// 行程规划参数
const city = ref("北京");
const days = ref(3);
const preferences = ref("历史,文化");

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit"
  });
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight;
    }
  });
};

// 发送行程规划请求
const sendItineraryRequest = async () => {
  if (!city.value.trim()) {
    ElMessage.warning("请输入目的地城市");
    return;
  }
  if (!days.value || days.value < 1) {
    ElMessage.warning("请选择有效的旅行天数（至少1天）");
    return;
  }

  const userMessage = `我想规划一个${days.value}天的${city.value}旅行，偏好：${preferences.value || "无明确偏好"}`;
  chatRecords.value.push({
    role: "user",
    content: userMessage,
    time: new Date().getTime()
  });
  scrollToBottom();

  try {
    isLoading.value = true;

    const resp = await api({
      url: "/api/v1/ai/chat",
      method: "get",
      params: {
        city: city.value,
        days: days.value,
        preferences: preferences.value
      },
      timeout: 90000,
      responseType: "text",
      headers
    });

    // ✅ 用 markdown-it 渲染
    const aiReply = resp ? md.render(resp) : "抱歉，未收到有效回复";
    chatRecords.value.push({
      role: "ai",
      content: aiReply,
      time: new Date().getTime()
    });

    if (headers.Authorization) {
      ElMessage.success("行程已生成并自动保存到您的账户中");
    }

  } catch (err) {
    console.error("请求失败:", err);
    let errorMessage = "请求失败，请稍后重试";

    if (err.code === 'ECONNABORTED') {
      errorMessage = "请求超时（90秒），请稍后再试";
    } else if (err.response && err.response.status === 401) {
      errorMessage = "身份验证失败，请重新登录";
    } else if (err.response && err.response.status === 500) {
      errorMessage = "服务器内部错误，请联系管理员";
    }

    chatRecords.value.push({
      role: "ai",
      content: errorMessage,
      time: new Date().getTime()
    });
    ElMessage.error(errorMessage);
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 清空聊天记录
const clearChat = () => {
  if (chatRecords.value.length === 0) {
    ElMessage.info("聊天记录已为空");
    return;
  }
  chatRecords.value = [];
  ElMessage.success("聊天记录已清空");
};

// 快捷填充
const fillSuggestion = (suggestCity, suggestDays, suggestPref) => {
  city.value = suggestCity;
  days.value = suggestDays;
  preferences.value = suggestPref;
  ElMessage.success(`已填充推荐：${suggestCity}${suggestDays}日游`);
};
</script>


<template>
  <!-- 统一容器：优化视觉包裹感 -->
  <div class="ai-chat-container">
    <!-- 头部：新增标题栏，提升辨识度 -->
    <div class="chat-header">
      <div class="header-inner">
        <div class="header-icon">
          <span class="icon-plane">✈️</span>
        </div>
        <div class="header-text">
          <h2>AI旅行定制助手</h2>
          <p>智能生成专属你的旅行计划</p>
        </div>
      </div>
      <ElButton
          type="text"
          class="clear-btn"
          @click="clearChat"
          :icon="Delete"
      >
        清空记录
      </ElButton>
    </div>

    <!-- 主体内容：左右布局优化 -->
    <div class="chat-main">
      <!-- 左侧：输入面板 - 优化间距和视觉层级 -->
      <div class="sidebar">
        <div class="sidebar-inner">
          <h3 class="sidebar-title">行程参数设置</h3>
          <p class="sidebar-desc">填写目的地、天数和偏好，获取精准行程</p>

          <!-- 输入组件：统一样式和间距 -->
          <ElInput
              v-model="city"
              placeholder="请输入目的地（如：成都）"
              :prefix-icon="Location"
              class="side-input"
              :maxlength="20"
              show-word-limit
              clearable
          />
          <ElInputNumber
              v-model="days"
              :min="1"
              :max="15"
              label="旅行天数"
              class="side-input"
              controls-position="right"
              :step="1"
          />
          <ElInput
              v-model="preferences"
              placeholder="请输入偏好（如：美食,古镇,爬山）"
              :prefix-icon="Star"
              class="side-input"
              :maxlength="50"
              show-word-limit
              clearable
          />

          <!-- 生成按钮：强化视觉焦点 -->
          <ElButton
              type="primary"
              :loading="isLoading"
              @click="sendItineraryRequest"
              :icon="Promotion"
              class="gen-btn"
              block
          >
            生成专属行程
          </ElButton>

          <!-- 新增：快捷推荐 - 提升用户体验 -->
          <div class="suggestions">
            <p class="suggest-title">热门推荐：</p>
            <div class="suggest-btn-group">
              <ElButton
                  type="text"
                  class="suggest-btn"
                  @click="fillSuggestion('成都', 4, '美食,熊猫,古镇')"
              >
                成都4日美食游
              </ElButton>
              <ElButton
                  type="text"
                  class="suggest-btn"
                  @click="fillSuggestion('杭州', 3, '西湖,自然,文化')"
              >
                杭州3日休闲游
              </ElButton>
              <ElButton
                  type="text"
                  class="suggest-btn"
                  @click="fillSuggestion('西安', 3, '历史,古迹,美食')"
              >
                西安3日历史游
              </ElButton>
              <ElButton
                  type="text"
                  class="suggest-btn"
                  @click="fillSuggestion('三亚', 5, '海滩,海岛,度假')"
              >
                三亚5日度假游
              </ElButton>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：结果面板 - 优化内容展示 -->
      <div class="result" ref="chatContent">
        <!-- 空状态：优化视觉效果 -->
        <div v-if="chatRecords.length === 0 && !isLoading" class="empty-state">
          <div class="empty-bg">
            <img
                src="D:\Java ws\TravelVue\src\assets\ai.jpg"
                alt="旅行风景"
                class="empty-bg-img"
            />
            <div class="empty-bg-overlay"></div>
          </div>
          <h3 class="empty-title">开启你的专属旅行计划</h3>
          <p class="empty-desc">
            输入目的地、旅行天数和兴趣偏好，AI将为你生成详细的每日行程安排，
            包含景点推荐、路线规划和游玩建议
          </p>
        </div>

        <!-- AI 行程展示：优化聊天气泡样式 -->
        <div v-else-if="chatRecords.length > 0" class="chat-list">
          <div
              v-for="(item, index) in chatRecords"
              :key="index"
              class="chat-item__wrap"
              :class="item.role === 'user' ? 'chat-item__wrap--user' : 'chat-item__wrap--ai'"
          >
            <!-- 头像：统一样式 -->
            <div class="chat-item__avatar" :class="`chat-item__avatar--${item.role}`">
              <ElAvatar size="small">
                <template v-if="item.role === 'ai'">
                  <img src="https://cdn-icons-png.flaticon.com/512/64/64572.png" alt="AI助手" />
                </template>
                <template v-else>
                  <User />
                </template>
              </ElAvatar>
            </div>

            <!-- 消息内容：优化气泡样式，支持HTML换行 -->
            <div class="chat-item__content">
              <div class="chat-item__bubble" v-html="item.content"></div>
              <div class="chat-item__time">
                {{ formatTime(item.time) }}
                <span v-if="item.role === 'ai'"> · AI助手</span>
                <span v-else> · 我</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载中：优化动画位置和样式 -->
        <div v-if="isLoading" class="loading">
          <div class="loading__typing">
            <span></span><span></span><span></span>
          </div>
          <p class="loading__text">AI正在为你生成行程计划...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局容器：统一视觉风格 */
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  overflow: hidden;
  max-width: 1400px;
  margin: 0 auto;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.03);
}

/* 头部：强化品牌感 */
.chat-header {
  background: linear-gradient(120deg, #4b6cb7 0%, #182848 100%);
  color: #fff;
  padding: 14px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  z-index: 10;
}
.header-inner {
  display: flex;
  align-items: center;
  gap: 12px;
}
.header-icon .icon-plane {
  font-size: 24px;
  opacity: 0.9;
}
.header-text h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
}
.header-text p {
  margin: 4px 0 0;
  font-size: 13px;
  opacity: 0.85;
}
.clear-btn {
  color: #fff;
  opacity: 0.8;
  transition: all 0.3s;
  padding: 6px 12px;
  border-radius: 6px;
}
.clear-btn:hover {
  opacity: 1;
  background: rgba(255, 255, 255, 0.15);
}

/* 主体内容：左右布局优化 */
.chat-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧输入面板：优化空间利用 */
.sidebar {
  width: 320px;
  background: rgba(255, 255, 255, 0.85);
  padding: 20px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.03);
  overflow-y: auto;
  backdrop-filter: blur(10px);
}
.sidebar-inner {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.sidebar-title {
  margin: 0;
  font-size: 16px;
  color: #1e293b;
  font-weight: 600;
}
.sidebar-desc {
  margin: 0;
  font-size: 13px;
  color: #64748b;
  line-height: 1.5;
}
.side-input {
  width: 100%;
  margin-bottom: 4px;
}
/* 输入框聚焦样式优化 */
.side-input .el-input__wrapper:focus-within {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1) !important;
  border-color: #3b82f6 !important;
}

/* 生成按钮：强化视觉焦点 */
.gen-btn {
  background: linear-gradient(120deg, #4b6cb7 0%, #182848 100%);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  padding: 12px;
  font-size: 14px;
  transition: all 0.3s;
  color: white;
}
.gen-btn:hover {
  background: linear-gradient(120deg, #3a5795 0%, #0f1c35 100%);
  box-shadow: 0 4px 12px rgba(75, 108, 183, 0.3);
}
.gen-btn.is-loading {
  background: linear-gradient(120deg, #4b6cb7 0%, #182848 100%);
}

/* 快捷推荐：提升用户引导 */
.suggestions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 8px;
}
.suggest-title {
  font-size: 14px;
  color: #475569;
  font-weight: 500;
  margin: 0;
}
.suggest-btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.suggest-btn {
  color: #4b6cb7;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.2s;
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(75, 108, 183, 0.2);
}
.suggest-btn:hover {
  color: #182848;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(75, 108, 183, 0.4);
}

/* 右侧结果面板：优化内容展示 */
.result {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(5px);
}
.result::-webkit-scrollbar {
  width: 6px;
}
.result::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 10px;
}
.result::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 10px;
}
.result::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 空状态：提升视觉吸引力 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #475569;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-top: 40px;
}
.empty-bg {
  width: 90%;
  height: 240px;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}
.empty-bg-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.empty-bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.3));
}
.empty-title {
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(120deg, #1e40af 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin: 0;
}
.empty-desc {
  font-size: 14px;
  opacity: 0.8;
  max-width: 600px;
  margin: 0;
  line-height: 1.6;
}

/* 聊天列表：优化布局 */
.chat-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 900px;
  margin: 0 auto;
}
.chat-item__wrap {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  max-width: 80%;
}
.chat-item__wrap--user {
  margin-left: auto;
  flex-direction: row-reverse;
}
.chat-item__avatar {
  margin-top: 4px;
}
.chat-item__avatar--ai .el-avatar {
  background: #e0f2fe;
  border: 1px solid #bae6fd;
  width: 36px;
  height: 36px;
}
.chat-item__avatar--user .el-avatar {
  background: #dbeafe;
  color: #3b82f6;
  border: 1px solid #bfdbfe;
  width: 36px;
  height: 36px;
}

/* 消息气泡：分层阴影 + 圆角细节 */
.chat-item__bubble {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.6;
  position: relative;
  animation: fadeIn 0.3s ease-out;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.chat-item__wrap--user .chat-item__bubble {
  background: linear-gradient(120deg, #4b6cb7 0%, #182848 100%);
  color: #fff;
  border-bottom-right-radius: 4px;
}
.chat-item__wrap--ai .chat-item__bubble {
  background: rgba(255, 255, 255, 0.8);
  color: #1e293b;
  border-bottom-left-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.5);
}

/* 消息时间：优化位置 + 透明度 */
.chat-item__time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 6px;
  text-align: right;
}
.chat-item__wrap--ai .chat-item__time {
  color: #64748b;
}

/* 加载动画：优化颜色 + 大小 */
.loading {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}
.loading__typing {
  display: flex;
  gap: 6px;
  justify-content: flex-start;
  padding-left: 8px;
}
.loading__typing span {
  width: 10px;
  height: 10px;
  background: #93c5fd;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}
.loading__typing span:nth-child(2) {
  animation-delay: 0.2s;
}
.loading__typing span:nth-child(3) {
  animation-delay: 0.4s;
}
.loading__text {
  font-size: 13px;
  color: #64748b;
  margin: 0;
  padding-left: 8px;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0.9);
    opacity: 0.7;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 响应式优化：适配移动端 */
@media (max-width: 768px) {
  .ai-chat-container {
    max-width: 100%;
  }

  .chat-main {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    max-height: 40vh;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }

  .result {
    flex: 1;
    padding: 16px;
  }

  .chat-item__wrap {
    max-width: 90%;
  }

  .empty-bg {
    height: 180px;
  }
}
/* Markdown 渲染美化 */
.chat-item__bubble h1,
.chat-item__bubble h2,
.chat-item__bubble h3,
.chat-item__bubble h4 {
  font-weight: 600;
  margin: 8px 0 6px;
  color: #1d4ed8;
}

.chat-item__bubble ul {
  margin: 6px 0;
  padding-left: 20px;
}

.chat-item__bubble li {
  margin: 4px 0;
  line-height: 1.6;
}

.chat-item__bubble p {
  margin: 4px 0;
  line-height: 1.6;
}

</style>
